const express = require('express')
const router = express.Router()
const { UserAddress } = require('../model/index')

router.post('/getaddress', (req, res) => {
  const { username } = req.body
  console.log(req)
  UserAddress.find({ username }).then(resp => {
    res.json({
      code: 200,
      data: resp
    })
  }).catch(err => {
    res.json({
      code: 400,
      data: err
    })
  })
})

router.post('/addaddress', (req, res) => {
  const { id, name, tel, country, isDefault, username, province, city, county, areaCode, postalCode, addressDetail } = req.body
  new UserAddress({ id, name, tel, country, isDefault, username, province, city, county, areaCode, postalCode, addressDetail })
    .save()
    .then(resp => {
      res.json({
        code: 200,
        data: {
          resp
        }
      })
    }).catch(err => {
      res.json({
        code: 400,
        data: {
          err
        }
      })
    })
})

router.post('/updateaddress', (req, res) => {
  const { id, name, tel, country, isDefault, username, province, city, county, areaCode, postalCode, addressDetail, _id } = req.body
  UserAddress.findOneAndUpdate({ _id }, { id, name, tel, country, isDefault, username, province, city, county, areaCode, postalCode, addressDetail })
    .then(resp => {
      res.json({
        code: 200,
        data: resp
      })
    }).catch(err => {
      res.json({
        code: 400,
        data: err
      })
    })
})

router.post('/deladdress', (req, res) => {
  const { _id } = req.body
  UserAddress.deleteOne({ _id })
    .then(resp => {
      res.json({
        code: 200,
        data: resp
      })
    }).catch((err) => {
      res.json({
        code: 400,
        data: err
      })
    })
})
module.exports = router